/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.crawl.parser;

import java.io.File;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.catalog.Label;
import com.koorz.modules.crawl.CrawlHistory;
import com.koorz.modules.crawl.CrawlWebsite;
import com.koorz.modules.crawl.http.SimpleHttpClient;
import com.koorz.modules.image.Image;
import com.koorz.modules.style.SimilarItems;
import com.koorz.modules.style.Style;
import com.koorz.modules.style.StyleItems;
import com.koorz.modules.user.User;
import com.koorz.utils.IdManage;
import com.koorz.utils.ImageUtil;
import com.koorz.utils.SystemConfig;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-5-27 下午8:50:58
 * 版  本  号：1.0
 */
public class TaskService {
	protected final Logger logger = Logger.getLogger(getClass());
	
	private static class SingletonHolder { 
		static final TaskService INSTANCE = new TaskService(); 
	}
	
	public static TaskService getInstance(){
		return SingletonHolder.INSTANCE;
	}
	
	private TaskService() {}
	
	public synchronized User saveUser(User u){
		User user = User.getUser("nickname", u.getStr("nickname"));
		if(user == null){
			User.saveUser(u);
			return u;
		}
		return user;
	}
	
	public synchronized Image saveImage(Image i){
		Image image = Image.getImage("source_id", i.getStr("source_id"));
		if(image == null){
			Image.saveImage(i);
			if(i.getInt("type") == Image.ImageType.SINGLE.ordinal()){
				i.set("buy_url", GlobalConstant.DOMAIN_HOST+"/goItem/"+i.getStr("id"));
				i.update();
			}
			return i;
		}
		return image;
	}
	
	public synchronized void addImageToCategory(String imageId,String categoryId){
		Record ic = Db.findFirst("select ic.* from category_image as ic " +
				" where ic.category_id=? and ic.image_id=?", categoryId,imageId);
		if(ic == null){
			ic = new Record();
			ic.set("id", IdManage.nextId(IdManage.CATEGORY_IMAGE));
			ic.set("image_id", imageId);
			ic.set("category_id", categoryId);
			Db.save("category_image", ic);
		}
	}
	
	public synchronized void addImageToLabel(String imageId,String labelName){
		Label label = Label.getLabel("name", labelName);
		Record ic = Db.findFirst("select il.* from label_image as il " +
				" where il.label_id=? and il.image_id=?", label.getStr("id"),imageId);
		if(ic == null){
			ic = new Record();
			ic.set("id", IdManage.nextId(IdManage.LABEL_IMAGE));
			ic.set("image_id", imageId);
			ic.set("label_id", label.getStr("id"));
			Db.save("label_image", ic);
		}
	}
	
	public synchronized void addImageToLabelGroup(String imageId,String labelGroupId){
		Record rec = Db.findFirst("select * from label_group_image where image_id=? and label_group_id=?", imageId,labelGroupId);
		if(rec == null){
			rec = new Record();
			rec.set("id", IdManage.nextId(IdManage.LABEL_GROUP_IMAGE));
			rec.set("image_id", imageId);
			rec.set("label_group_id", labelGroupId);
			Db.save("label_group_image", rec);
		}
	}
	
	public synchronized Style addStyle(Style s){
		Style style = Style.dao.findFirst("select * from style where image_id=? and user_id=?", s.getStr("image_id"),s.getStr("user_id"));
		if(style == null){
			Style.saveStyle(s);
			return s;
		}
		return style;
	}
	
	public synchronized void addStyleItems(StyleItems s){
		StyleItems item = StyleItems.dao.findFirst("select * from style_items " +
				" where style_id=? and image_id=?", s.getStr("style_id"),s.getStr("image_id"));
		if(item == null){
			StyleItems.saveStyleItems(s);
		}
	}
	
	public synchronized void addSimilarItems(SimilarItems s){
		SimilarItems item = SimilarItems.dao.findFirst("select * from similar_items " +
				" where image_id=? and item_id=?", s.getStr("image_id"),s.getStr("item_id"));
		if(item == null){
			SimilarItems.saveSimilarItems(s);
		}
	}
	
	public synchronized void compressAvatar(SimpleHttpClient client,User user) throws Exception{
		User temp = User.dao.findById(user.getStr("id"));
		if(!StringUtils.contains(temp.getStr("avatar_large"),"http://static.koorz.com")){
			String avatarLarge = client.downloadFile(user.getStr("avatar_large"), user.getStr("id")+"_normal");
			if(StringUtils.isEmpty(avatarLarge)){
				return;
			}
			String type = "." + StringUtils.substringAfterLast(avatarLarge, ".");
			String dir = String.format(SystemConfig.getValue("user.avatar_dir"), user.getStr("id"));
			String fullpath = dir + "/"+user.getStr("id");
			String large = fullpath+"_large"+ type;
			String avatar = fullpath+"_small"+ type;
//			JSONObject jsonObj = ImageUtil.saveAvatar(avatarLarge, large, ImageUtil.AVATAR_LARGE_WIDTH, ImageUtil.AVATAR_LARGE_HEIGHT,user.getStr("id"));
//			user.set("avatar_large", jsonObj.getString("url"));
//			jsonObj = ImageUtil.saveAvatar(avatarLarge, avatar, ImageUtil.AVATAR_WIDTH, ImageUtil.AVATAR_HEIGHT,user.getStr("id"));
//			user.set("avatar", jsonObj.getString("url"));
//			user.update();
//			ImageUtil.delFile(avatarLarge);
		}
	}
	
	public synchronized void compressImage(SimpleHttpClient client,Image image) throws Exception{
		Image temp = Image.dao.findById(image.getStr("id"));
		if(!StringUtils.contains(temp.getStr("url"),"http://static.koorz.com")){
			String srcpath = client.downloadFile(image.getStr("url"), image.getStr("id")+"_normal");
			if(StringUtils.isEmpty(srcpath)){
				return;
			}
			String type = "." + StringUtils.substringAfterLast(srcpath, ".");
			String dir = SystemConfig.getValue("img_dir") + "/"+image.getStr("id");
			String url = GlobalConstant.RESOURCES_HOST+"/images/"+new File(srcpath).getName();
			String detail_url = dir+"_detail"+ type;
			String waterfall_url = dir+"_waterfall"+ type;
			String similar_url = dir+"_similar"+ type;
			String item_url = dir+"_item"+ type;
			String style_url = dir+"_style"+ type;
//			if(image.getInt("type") == Image.ImageType.SINGLE.ordinal()){
//				JSONObject jsonObj = ImageUtil.saveImage(srcpath, style_url, ImageUtil.STYLE_WIDTH, ImageUtil.STYLE_HEIGHT);
//				image.set("style_url", jsonObj.getString("url"));
//				image.set("style_width", jsonObj.getString("width"));
//				image.set("style_height", jsonObj.getString("height"));
//				
//				jsonObj = ImageUtil.saveImage(srcpath, item_url, ImageUtil.ITEM_WIDTH, null);
//				image.set("item_url", jsonObj.getString("url"));
//				image.set("item_width", jsonObj.getString("width"));
//				image.set("item_height", jsonObj.getString("height"));
//			}
//			
//			JSONObject jsonObj = ImageUtil.saveImage(srcpath, similar_url, ImageUtil.SIMILAR_WIDTH, ImageUtil.SIMILAR_HEIGHT);
//			image.set("similar_url", jsonObj.getString("url"));
//			image.set("similar_width", jsonObj.getString("width"));
//			image.set("similar_height", jsonObj.getString("height"));
//			
//			jsonObj = ImageUtil.saveImage(srcpath, waterfall_url, ImageUtil.WATERFALL_WIDTH, null);
//			image.set("waterfall_url", jsonObj.getString("url"));
//			image.set("waterfall_width", jsonObj.getString("width"));
//			image.set("waterfall_height", jsonObj.getString("height"));
//			
//			jsonObj = ImageUtil.saveImage(srcpath, detail_url, ImageUtil.DETAIL_WIDTH, null);
//			image.set("detail_url", jsonObj.getString("url"));
//			image.set("detail_width", jsonObj.getString("width"));
//			image.set("detail_height", jsonObj.getString("height"));
			
			image.set("url", url);
			image.update();
		}
	}
	
	public synchronized void addCrawlHistory(CrawlHistory c){
		CrawlHistory item = CrawlHistory.dao.findFirst("select * from crawl_history where url=?", c.getStr("url"));
		if(item == null){
			CrawlHistory.saveCrawlHistory(c);
		}
	}
	
	public synchronized void addCrawlWebsite(CrawlWebsite c){
		CrawlWebsite item = CrawlWebsite.dao.findFirst("select * from crawl_website where url=?", c.getStr("url"));
		if(item == null){
			CrawlWebsite.saveCrawlWebsite(c);
		}
	}
}
